package jcu.ict.profaid;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint("NewApi")
public class FormResultTable extends Activity{
	private AnswerDbAdapter adb;
	private QuestionDbAdapter qdb;
	private Cursor aCursor;
	private String questionID;
	private TableLayout table;
	private View btnCalButton;
	private String courseID;
	private String user_id;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form_table);
		
		adb = new AnswerDbAdapter(getBaseContext());
		qdb = new QuestionDbAdapter(getBaseContext());
		
		Bundle bundle = this.getIntent().getExtras();
		questionID = bundle.getString("setQuestionId");
		courseID = bundle.getString("setCourseId");
		user_id = (String) bundle.getCharSequence("setUserId");
		
		
		btnCalButton = findViewById(R.id.btnCal);
		table = (TableLayout) findViewById(R.id.tableLayout);
		
		adb.open();
		qdb.open();
		
		tableOfResult();
		
		btnCalButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				adb.open();
				qdb.open();
				initViews();
				
				table.removeAllViews();

				Cursor xCursor = qdb.populateQuestionDesc(questionID);
				xCursor.moveToFirst();

				aCursor = adb.PopulateAnswer(user_id,questionID);
				aCursor.moveToFirst();

				tableOfResult();
				
				adb.close();
				qdb.close();
			}
		});
		
		adb.close();
		qdb.close();
	}
	
	private void tableOfResult(){
		
		table.setScrollbarFadingEnabled(true);
		table.setScrollContainer(true);
		table.setStretchAllColumns(true);  
		table.setShrinkAllColumns(true); 
		table.setPadding(5, 5, 5, 5);

		TableRow.LayoutParams llp = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
		llp.setMargins(1, 0, 0, 0);
		table.setColumnShrinkable(1, true);

		String arrHeader[] = {"Answer ID","Answer","Sum"};

		TableRow trHead = new TableRow(this);
		trHead.setBackgroundColor(Color.WHITE);
		trHead.setPadding(0,0,0,10);
		

		for(int i=0;i<3;i++){		
			LinearLayout cell = new LinearLayout(this);
			cell.setBackgroundColor(Color.parseColor("#0099CC"));
			cell.setLayoutParams(llp);//2px border on the right for the cell
			
			TextView tv = new TextView(this);
			tv.setText(arrHeader[i]);
			tv.setPadding(5, 5, 0, 0);
			tv.setTextColor(Color.WHITE);
			tv.setTypeface(null, Typeface.BOLD);

			cell.addView(tv);
			trHead.addView(cell);
		}
		table.addView(trHead);
		
		fillTable(table, llp);
		
	} 
	
	@SuppressWarnings("deprecation")
	@SuppressLint({ "NewApi", "InlinedApi" })
	private void fillTable(TableLayout table,TableRow.LayoutParams llp){
        try{
                aCursor = adb.TableAnswer(questionID);
                aCursor.moveToFirst();
                for(int j=0;j<aCursor.getCount();j++){
                        TableRow tr = new TableRow(this);
                        tr.setBackgroundColor(Color.BLACK);
                        tr.setPadding(0, 0, 0, 1); //Border between rows

                        //New Cell
                        for(int i=0;i<aCursor.getColumnCount();i++){            
                                LinearLayout cell = new LinearLayout(this);
                                cell.setBackgroundColor(Color.WHITE);
                                cell.setLayoutParams(llp);//2px border on the right for the cell
                                cell.layout(10, 10, 10, 10);
                               
                                TextView tv = new TextView(this);
                               
                                tv.setSingleLine(false);
                               
                                if(i>1 || i<1){
                                        tv.setLayoutParams(new LayoutParams(65, LayoutParams.FILL_PARENT));
                                        tv.setGravity(Gravity.CENTER);
                                        tv.setText(aCursor.getString(i));
                                }
                                else{
                                        tv.setText(aCursor.getString(i));
                                        tv.setLayoutParams(new LayoutParams(350, LayoutParams.FILL_PARENT));
                                }
                               
                                tv.setPadding(5, 0, 0, 5);
                                tv.setTextColor(Color.BLACK);
                                cell.addView(tv);
                                tr.addView(cell);
                        }
                        //add as many cells you want to a row, using the same approach

                        table.addView(tr);
                        aCursor.moveToNext();

                }
        }catch(Exception e){
                Toast.makeText(this.getBaseContext(), "ex: "+e.toString(), Toast.LENGTH_LONG).show();
        }

}
	
	public void initViews() {
		Cursor iTimeDate = adb.getTimeCompare();
		iTimeDate.moveToFirst();

		long dTime = iTimeDate.getLong(0);

		Uri uriSms = Uri.parse("content://sms/inbox");
		Cursor cursor = getContentResolver().query(uriSms,
				new String[] { "_id", "address", "date", "body" },
				"date" + ">" + dTime, null, null);

		String body;
		String smsId;

		if (cursor.moveToFirst()) {
			adb.updateTimeFlag(cursor.getLong(2));
			do {
				body = cursor.getString(3);
				smsId = cursor.getString(0);
				if (checkSMSvalue(body) == true) {
					deleteSms(smsId);
				}
			} while (cursor.moveToNext());
		} else {
		}
	}

	public boolean checkSMSvalue(String answer) {
		boolean check = false;
		try {
			int iAnswer = Integer.parseInt(answer);

			Cursor cAnswer = adb.getAnswer(iAnswer);
			cAnswer.moveToFirst();

			for (int i = 0; i < cAnswer.getCount(); i++)
				for (int j = 0; j < cAnswer.getColumnCount(); j++) {
					Cursor cAnswerSum = adb.getSum(cAnswer.getInt(j));
					cAnswerSum.moveToFirst();

					int x = cAnswerSum.getInt(0);

					if (adb.updateAnswerSum(cAnswer.getInt(j), x)) {
						check = true;
						Toast.makeText(this, "Update successful.",
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(this, "Update failed.",
								Toast.LENGTH_LONG).show();
					}
				}
		} catch (Exception e) {
		}
		return check;
	}

	public boolean deleteSms(String smsId) {
		boolean isSmsDeleted = false;
		try {
			this.getContentResolver().delete(
					Uri.parse("content://sms/" + smsId), null, null);
			isSmsDeleted = true;

		} catch (Exception ex) {
			isSmsDeleted = false;
		}
		return isSmsDeleted;
	}

	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	    	Intent in = new Intent(FormResultTable.this,MainQuestion.class);
			Bundle bundle = new Bundle();
			bundle.putString("setInfoCourse", courseID);
			bundle.putCharSequence("setUserId", user_id);
            in.putExtras(bundle);
			startActivity(in);
			finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}
}
